package com.ly.hotel.spainterface.nm;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.nm.bean.NmXFBuyItemBean;
import com.ly.hotel.spainterface.nm.bean.NmXFHnadCardBean;
import com.ly.hotel.spainterface.nm.bean.NmXFItemBean;
import com.ly.hotel.spainterface.nm.bean.NmXFTypeBean;
import com.ly.hotel.spainterface.nm.event.XFBuyReqEvent;
import com.ly.hotel.spainterface.nm.event.XFBuyResEvent;
import com.ly.hotel.spainterface.nm.event.XFReqCardEvent;
import com.ly.hotel.spainterface.nm.event.XFResCardEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateCartEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateItemHideEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateItemHideResEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateTypeHideEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateTypeHideResEvent;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.MlistView;
import com.ly.hotel.view.common.BaseActivity;
import com.ly.hotel.webagent.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import de.greenrobot.event.EventBus;

public class NmXiaoFeiActivity extends BaseActivity {

    private static final String TAG = "NmXiaoFeiActivity";
    private NmXFTypeAdapter xfTypeListAdapter;
    private RelativeLayout myxfLayout;

    private MlistView xfTypeListView;

    private List<NmXFTypeBean> xiaofeiTypeList = new ArrayList<>();
    private NmXFTypeBean typeSelect = null;

    private GridView mGrid;

    private TextView totalText;
    private TextView nameText;
    private TextView cartCountText;
    private TextView title;
    private ImageButton shopCartBt;

    private List<NmXFItemBean> recycleviewList = new ArrayList<>();
    private MyApplication app;


    private ThisHandler handlerMsg = new ThisHandler(this);

    private LinearLayout typeDownMore;
    private ImageView itemDownMore;

    //消费配置
    private String interfaceIp;
    private String interfacePort;
    private int drinkCount = 1;
    private int snackCount = 1;
    private int saleCount = 1;

    public static final int GET_TYPE = 1;
    public static final int GET_ITEM = 2;
    public static final int GET_HAND = 3;
    public static final int GET_WAITER = 4;
    public static final int GET_BUY = 5;
    public static final int GET_TYPE_HIDE = 6;
    public static final int GET_TYPE_SORT = 7;
    public static final int GET_ITEM_HIDE = 8;
    public static final int GET_ITEM_SORT = 9;
    public static final int SET_TYPE_HIDE = 10;
    public static final int SET_TYPE_SORT = 11;
    public static final int SET_ITEM_HIDE = 12;
    public static final int SET_ITEM_SORT = 13;

    private String typeHideArr;
    private String typeSortArr;
    private String itemHideArr;
    private String itemSortArr;

    private String lang;

    private NmXFItemAdapter mAdapter;

    private static final Gson gson = new GsonBuilder().create();

    private List<NmXFBuyItemBean> buyList;
    private Animation scaleAnimation;
    private PathMeasure mPathMeasure;
    private float[] mCurrentPosition = new float[2];
    private int selectPos = -1;
    private int top;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiaofei_nm);
        app = (MyApplication) getApplicationContext();
        scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_anim);
        top = getResources().getDimensionPixelSize(R.dimen.px15);
        initInterfaceConf();
        findView();
        setListener();
        setCartCount();
        // 获取消费类别
        getTypeList();
    }

    @Override
    public void onPause() {
        if (handlerMsg.hasMessages(GET_TYPE)) {
            handlerMsg.removeMessages(GET_TYPE);
        }
        if (handlerMsg.hasMessages(GET_ITEM)) {
            handlerMsg.removeMessages(GET_ITEM);
        }
        super.onPause();
    }

    //解析接口配置
    private void initInterfaceConf() {
        if (LanguageUtil.isEN()) {
            lang = "en";
        } else {
            lang = "cn";
        }
        try {
            DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder dombuilder = domfac.newDocumentBuilder();
            Document doc = dombuilder.parse(new ByteArrayInputStream(MyApplication.pluginCfg.getBytes("utf-8")));
            NodeList obj = doc.getElementsByTagName(MyApplication.interfaceVersion);

            NodeList sysList = ((Element) obj.item(0)).getElementsByTagName("xiaofei");

            if (sysList.getLength() >= 1) {
                NodeList headList = ((Element) sysList.item(0)).getElementsByTagName("ip");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    interfaceIp = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("port");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    interfacePort = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("drinkCount");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    try {
                        drinkCount = Integer.parseInt(headList.item(0).getFirstChild().getNodeValue());
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "drinkCount配置有误！", Toast.LENGTH_SHORT).show();
                    }
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("snackCount");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    try {
                        snackCount = Integer.parseInt(headList.item(0).getFirstChild().getNodeValue());
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "snackCount配置有误！", Toast.LENGTH_SHORT).show();
                    }
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("saleCount");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    try {
                        saleCount = Integer.parseInt(headList.item(0).getFirstChild().getNodeValue());
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "saleCount配置有误！", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void findView() {
        myxfLayout =  findViewById(R.id.my_xf_activity);
        mGrid = findViewById(R.id.mXFRecycle);
        totalText = findViewById(R.id.xf_count);
        nameText = findViewById(R.id.xf_count_name);
        cartCountText = findViewById(R.id.xf_shop_cart_count);
        xfTypeListView = findViewById(R.id.movieTypeListViewA);
        typeDownMore = findViewById(R.id.down_more);
        itemDownMore = findViewById(R.id.xf_down_more);
        shopCartBt = findViewById(R.id.xf_shopCar);
        title = findViewById(R.id.act_title).findViewById(R.id.activity_name);
        title.setText(R.string.naviXiaofeiName);
    }

    //消费类别
    private void getTypeList() {
        typeSelect = null;
        xiaofeiTypeList.clear();
        ProcessWaitingUtil.showProcessDialog(NmXiaoFeiActivity.this, "Loading...", 5000);
        if (app.nmXFTypeList.size() == 0) {
            toHttpGet(GET_TYPE, null, null, null);
        } else {
            toHttpGet(GET_TYPE_HIDE,null);
        }
    }

    //获取服务器存储数据，类别的排序，估清，项目的
    private void toHttpGet(int type,final String typeId){
        switch (type) {
            case GET_TYPE_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=NM_XFHotelClassHide";
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_TYPE_HIDE;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_TYPE_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=NM_XFHotelClassSort";
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_TYPE_SORT;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_ITEM_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=NM_XFHotelItemHide";
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);

                        int id = 0;
                        try {
                            id = Integer.parseInt(typeId);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = GET_ITEM_HIDE;
                        msg.arg1 = id;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_ITEM_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=NM_XFHotelItemSort" + typeId;
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        int id = 0;
                        try {
                            id = Integer.parseInt(typeId);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }

                        Message msg = new Message();
                        msg.what = GET_ITEM_SORT;
                        msg.arg1 = id;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case SET_TYPE_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
                        String request = "filename=NM_XFHotelClassHide&content=" + typeHideArr;
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = SET_TYPE_HIDE;
                        msg.arg1 = 1;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case SET_TYPE_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
                        String request = "filename=NM_XFHotelClassSort&content=" + typeSortArr;
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = SET_TYPE_SORT;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case SET_ITEM_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
                        String request = "filename=NM_XFHotelItemHide&content=" + itemHideArr;
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = SET_ITEM_HIDE;
                        msg.arg1 = 1;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case SET_ITEM_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-write.json";
                        String request = "filename=NM_XFHotelItemSort" + typeId + "&content=" + itemSortArr;
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = SET_ITEM_SORT;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
        }
    }

    //接口的http请求
    private void toHttpGet(int type, final String typeId, final String cardId, final String keyno) {
        final String URL = "http://" + interfaceIp + ":" + interfacePort + "/API/index.aspx";
        switch (type) {
            case GET_TYPE:        //获取消费类型
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String request = "mid=4002&lang=" + lang;
                        String str = new String(request.replace(" ", "%20"));
                        Log.i("httpGet", URL + str);
                        String sendRes = HttpRequest.sendGet(URL, str);
                        Message msg = new Message();
                        msg.what = GET_TYPE;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_ITEM:        //获取消费项目
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String request = "mid=4003&m_s_no=" + typeId + "&lang=" + lang;
                        String str = new String(request.replace(" ", "%20"));
                        Log.i("httpGet", URL + str);
                        String sendRes = HttpRequest.sendGet(URL, str);
//                        sendRes = getJson(NmXiaoFeiActivity.this, typeSelect.getId() + ".json");
                        int id = 0;
                        try {
                            id = Integer.parseInt(typeId);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = GET_ITEM;
                        msg.arg1 = id;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_HAND:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String request = "mid=3001&idno=" + cardId + "&lang=" + lang;
                        String str = new String(request.replace(" ", "%20"));
                        Log.i("httpGet", URL + str);
                        String sendRes = HttpRequest.sendGet(URL, str);
                        Message msg = new Message();
                        msg.what = GET_HAND;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_WAITER:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String request = "mid=3003&idno=" + cardId + "&lang=" + lang;
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_WAITER;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_BUY:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JsonObject buyobj = new JsonObject();
                        buyobj.addProperty("as_table", urlParse(MyApplication.getDeviceInfo().getName()));
                        buyobj.addProperty("as_empno", "pretv");
                        JsonArray buyarr = new JsonArray();
                        for (NmXFBuyItemBean bb : buyList) {
                            JsonObject bo = new JsonObject();
                            bo.addProperty("as_no", bb.getId());
                            bo.addProperty("as_describe", urlParse(bb.getName()));
                            bo.addProperty("an_price", bb.getPrice() + "");
                            bo.addProperty("an_count", bb.getNum() + "");
                            bo.addProperty("action_name", urlParse(bb.getAction()));
                            buyarr.add(bo);
                        }
                        buyobj.add("as_item", buyarr);
                        String request = "mid=4099&datas=" + buyobj.toString() + "&lang=" + lang;
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_BUY;
                        msg.obj = sendRes;
                        handlerMsg.sendMessage(msg);
                    }
                }).start();
                break;
        }
    }

    private String urlParse(String name) {
        String newName = "";
        try {
            newName = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return newName;
    }

    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        //获得assets资源管理器
        AssetManager assetManager = context.getAssets();
        //使用IO流读取json文件内容
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    //解析接口服务器数据
    private void parseResData(int type, String parseStr,int tid) {
        try {
            JSONObject jsObj = new JSONObject(parseStr);
            String suc = jsObj.getString("success");
            if (suc.equals("true")) {
                if (type != GET_BUY) {
                    JSONArray arr = jsObj.getJSONArray("data");
                    switch (type) {
                        case GET_TYPE:
                            app.nmXFTypeList.clear();
                            for (int i = 0; i < arr.length(); i++) {
                                JSONObject lan = arr.getJSONObject(i);
                                NmXFTypeBean b = gson.fromJson(lan.toString(), NmXFTypeBean.class);
                                app.nmXFTypeList.add(b);
                            }
                            toHttpGet(GET_TYPE_HIDE,null);
                            break;
                        case GET_ITEM:
                            for (int i = 0; i < arr.length(); i++) {
                                JSONObject lan = arr.getJSONObject(i);
                                NmXFItemBean b = gson.fromJson(lan.toString(), NmXFItemBean.class);
                                typeSelect.setTypeItems(b);
                            }
                            toHttpGet(GET_ITEM_HIDE,typeSelect.getId());
                            break;
                        case GET_HAND:
                            String errmsg = getResources().getString(R.string.xf_call_waiter);
                            if (arr.length() > 0) {
                                JSONObject lan = arr.getJSONObject(0);
                                NmXFHnadCardBean b = gson.fromJson(lan.toString(), NmXFHnadCardBean.class);
                                if (b.getIssue().equals("Y")) {
                                    EventBus.getDefault().post(new XFResCardEvent(1, true, b.getKeyno()));
                                } else {
                                    EventBus.getDefault().post(new XFResCardEvent(1, false, errmsg));
                                }
                            } else {
                                EventBus.getDefault().post(new XFResCardEvent(1, false, errmsg));
                            }
                            break;
                        case GET_WAITER:
                            EventBus.getDefault().post(new XFResCardEvent(2, true, null));
                            break;
                        default:
                            break;
                    }
                } else {
                    ProcessWaitingUtil.closeProcessDialog();
                    EventBus.getDefault().post(new XFBuyResEvent(true));
                }
            } else {
                ProcessWaitingUtil.closeProcessDialog();
                String errmsg = jsObj.getString("errorMessage");
                if (type == GET_HAND) {
                    EventBus.getDefault().post(new XFResCardEvent(1, false, errmsg));
                } else if (type == GET_BUY) {
                    EventBus.getDefault().post(new XFBuyResEvent(false));
                } else {
                    ToastUtil.showShortToast(this, errmsg, 5000);
                }
            }
        } catch (JSONException e) {
            ProcessWaitingUtil.closeProcessDialog();
            String errmsg = getResources().getString(R.string.connect_err);
            if (type == GET_HAND) {
                EventBus.getDefault().post(new XFResCardEvent(1, false, errmsg));
            } else if (type == GET_BUY) {
                EventBus.getDefault().post(new XFBuyResEvent(false));
            } else {
                ToastUtil.showShortToast(this, errmsg, 5000);
            }
        }
    }

    //解析SPA服务器数据
    private void parseResData(String parseStr,int tid,int type) {
        switch (type) {
            case GET_TYPE_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        typeHideArr = data;
                    }else{
                        typeHideArr = null;
                    }
                } catch (JSONException e) {
                    typeHideArr = null;
                    Log.e(TAG,e.getMessage());
                }
                toHttpGet(GET_TYPE_SORT,null);
                break;
            case GET_TYPE_SORT:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        typeSortArr = data;
                    }else{
                        typeSortArr = null;
                    }
                } catch (JSONException e) {
                    typeSortArr = null;
                    Log.e(TAG,e.getMessage()+"");
                }
                updateTypeList();
                updateTypeListView();
                break;
            case GET_ITEM_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        itemHideArr = data;
                    }else{
                        itemHideArr = null;
                    }
                } catch (JSONException e) {
                    itemHideArr = null;
                }
                toHttpGet(GET_ITEM_SORT,typeSelect.getId());
                break;
            case GET_ITEM_SORT:
                NmXFTypeBean sortSelect = typeSelect;
                String sortId = tid+"";
                if(tid != 0){
                    for(NmXFTypeBean b : app.nmXFTypeList){
                        if(b.getId().equals(sortId)){
                            sortSelect = b;     //找到选择的类型
                            break;
                        }
                    }
                }
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        sortSelect.setSortItems(data);
                    }else{
                        sortSelect.setSortItems(null);
                    }
                } catch (JSONException e) {
                    sortSelect.setSortItems(null);
                }
                updateXFItemList(sortSelect);
                updateXFItemView();
                break;
            case SET_TYPE_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    if (code == 200) {
                        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
                        getTypeList();
                    }else{
                        Toast.makeText(this,"失败：" + parseStr,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(this,"失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                }
                break;
            case SET_TYPE_SORT:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    if (code == 200) {
                        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
                        getTypeList();
                    }else{
                        Toast.makeText(this,"失败：" + parseStr,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(this,"失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                }
                break;
            case SET_ITEM_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    if (code == 200) {
                        String iId = typeSelect.getId();
                        toHttpGet(GET_ITEM_HIDE,iId);
                        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this,"失败：" + parseStr,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(this,"失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                }
                break;
            case SET_ITEM_SORT:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    if (code == 200) {
                        String iId = typeSelect.getId();
                        toHttpGet(GET_ITEM_HIDE,iId);
                        Toast.makeText(this,"成功",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this,"失败：" + parseStr,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(this,"失败：" + e.getMessage(),Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    public String getTypeSortArr(){
        return typeSortArr;
    }

    public NmXFTypeBean getSelectBean(){
        return typeSelect;
    }

    private void updateTypeList(){
        xiaofeiTypeList.clear();
        if(!TextUtils.isEmpty(typeSortArr)){
            try {
                JSONArray arr = new JSONArray(typeSortArr);
                for (int i = arr.length() -1; i >= 0; i--) {
                    String lan = arr.getString(i);
                    for (NmXFTypeBean b : app.nmXFTypeList) {
                        if(lan.equals(b.getId())) {
                            app.nmXFTypeList.remove(b);
                            app.nmXFTypeList.add(0,b);
                            break;
                        }
                    }
                }
            }catch (JSONException e){
                Log.e(TAG,e.getMessage());
            }
        }

        if(!TextUtils.isEmpty(typeHideArr)) {
            for (NmXFTypeBean b : app.nmXFTypeList) {
                if (!typeHideArr.contains(b.getId())) {
                    b.setShow(true);
                    xiaofeiTypeList.add(b);
                } else {
                    b.setShow(false);
                }
            }
        }else{
            xiaofeiTypeList.addAll(app.nmXFTypeList);
        }
    }

    private void updateTypeListView() {
        // 使用自定义的Adapter
        if(xfTypeListAdapter == null) {
            xfTypeListAdapter = new NmXFTypeAdapter(this, xiaofeiTypeList);
            xfTypeListView.setAdapter(xfTypeListAdapter);
        }else{
            xfTypeListAdapter.notifyDataSetChanged();
        }
        EventBus.getDefault().post(new XFUpdateTypeHideResEvent());


        if (xiaofeiTypeList.size() >= 1) {
            //模拟第一行点击
            xfTypeListView.post(new Runnable() {
                public void run() {
                    int count = xfTypeListView.getChildCount();
                    if (count != 0) {
                        xfTypeListView.performItemClick(xfTypeListView.getChildAt(0),
                                0, xfTypeListView.getItemIdAtPosition(0));
                        xfTypeListView.requestFocus();
                        xfTypeListView.requestFocusFromTouch();
                        xfTypeListView.setSelection(0);
                    }
                }

            });
        }
    }

    public void setOnclickBean(String id){
        int pos = -1;
        for (int i =0;i<xiaofeiTypeList.size();i++){
            if(xiaofeiTypeList.get(i).getId().equals(id)){
                pos = i;
                break;
            }
        }
        final int position = pos;
        xfTypeListView.setSelection(pos);
        xfTypeListView.post(new Runnable() {
            public void run() {
                if(position != -1) {
                    int visiblePosition = xfTypeListView.getFirstVisiblePosition();
                    //得到指定位置的视图
                    View view = xfTypeListView.getChildAt(position - visiblePosition);
                    xfTypeListView.performItemClick(view, position, xfTypeListView.getItemIdAtPosition(position));
                }
            }
        });
    }

    private void updateXFItemList(NmXFTypeBean itempart) {
        if (itempart.getTypeItems() != null) {
            List<NmXFItemBean> list = itempart.getTypeItems();
            recycleviewList.clear();
            String sortItems = itempart.getSortItems();
            if(!TextUtils.isEmpty(sortItems)){
                try {
                    JSONArray arr = new JSONArray(sortItems);
                    for (int i = arr.length() -1; i >= 0; i--) {
                        String lan = arr.getString(i);
                        for (NmXFItemBean b : list) {
                            if(lan.equals(b.getId())) {
                                list.remove(b);
                                list.add(0,b);
                                break;
                            }
                        }
                    }
                }catch (JSONException e){

                }
            }

            if(!TextUtils.isEmpty(itemHideArr)){
                for(NmXFItemBean lb:list) {
                    if (!itemHideArr.contains(lb.getId())){
                        lb.setShow(true);
                        recycleviewList.add(lb);
                    }else{
                        lb.setShow(false);
                    }
                }
            }else{
                recycleviewList.addAll(list);
            }
        }
    }

    private void updateXFItemView() {
        if (recycleviewList != null && typeSelect != null) {
            nameText.setText(typeSelect.getName());
            totalText.setText(recycleviewList.size() + "");
        }
        selectPos = -1;
        if (mAdapter == null) {
            mAdapter = new NmXFItemAdapter(this, recycleviewList);
            mGrid.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mGrid.post(new Runnable() {
            @Override
            public void run() {
                mGrid.setSelection(0);
                mGrid.smoothScrollToPositionFromTop(0,0);
                ProcessWaitingUtil.closeProcessDialog();
            }
        });
        EventBus.getDefault().post(new XFUpdateItemHideResEvent());     //通知操作页面更新
    }

    private void setListener() {
        title.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                StaffSwipeDialog swipeDialog = new StaffSwipeDialog(NmXiaoFeiActivity.this, R.style.introDialog);
                swipeDialog.setCanceledOnTouchOutside(true);
                swipeDialog.show();
                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                        MyApplication.interfaceVersion + "\t" + "商品操作"));
                return false;
            }
        });

        xfTypeListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                NmXFTypeAdapter.ViewHolder holder = (NmXFTypeAdapter.ViewHolder) view.getTag();
                xfTypeListAdapter.setSelectedPosition(pos);
                if (typeSelect != holder.v) {
                    typeSelect = holder.v;
                    // 有数据就请求SPA服务器估清和排序数据
                    String iId = holder.v.getId();
                    ProcessWaitingUtil.showProcessDialog(NmXiaoFeiActivity.this, "Loading...", 5000);
                    if (typeSelect.getTypeItems() != null) {
                        toHttpGet(GET_ITEM_HIDE,iId);
                    } else {// 没数据就请求接口服务器数据
                        //清空掉，这样不会有残留上一个分类的视频
                        if (recycleviewList != null) {
                            recycleviewList.clear();
                        }

                        toHttpGet(GET_ITEM, iId, null, null);
                    }
                }
            }
        });

        xfTypeListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            /* (non-Javadoc)
             * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
             */
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
                if ((arg1 == 0 && arg2 == arg3) || (arg1 > 0 && arg1 + arg2 == arg3)) {
                    typeDownMore.setVisibility(View.GONE);
                } else {
                    typeDownMore.setVisibility(View.VISIBLE);
                }
            }
        });

        mGrid.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showItemDialog(recycleviewList.get(position));
            }
        });

        mGrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(selectPos != -1) {
                    int dValue = selectPos - position;
                    if (dValue == 4) {
                        if(position > 3) {
                            mGrid.smoothScrollToPositionFromTop(position -4,-top);
                        }else{
                            mGrid.smoothScrollToPositionFromTop(0,0);
                        }
                    } else if (dValue == -4) {
                        if(position > 3) {
                            mGrid.smoothScrollToPositionFromTop(position,top);
                        }else{
                            mGrid.smoothScrollToPositionFromTop(0,0);
                        }
                    }
                }
                selectPos = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectPos = -1;
            }
        });


        mGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState == 0){
                    ImageLoader.getInstance().resume();
                }else{
                    ImageLoader.getInstance().pause();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if((firstVisibleItem + visibleItemCount) == totalItemCount){
                    itemDownMore.setVisibility(View.INVISIBLE);
                }else{
                    itemDownMore.setVisibility(View.VISIBLE);
                }
            }
        });

        shopCartBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XFShopCartDialog xfShopCartDialog = new XFShopCartDialog(NmXiaoFeiActivity.this, R.style.introDialog, app.shopCartList);
                xfShopCartDialog.setCanceledOnTouchOutside(true);
                xfShopCartDialog.show();
                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                        MyApplication.interfaceVersion + "\t" + "查看购物篮"));
            }
        });
    }

    //找到数组中的最大值
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

    //显示消费详情
    public void showItemDialog(NmXFItemBean item) {
        int count = getMaxBuyCount(item.getType());
        String typeName = getItemTypeName(item.getType());
        XFItemDetailsDialog detailsDialog = new XFItemDetailsDialog(this, R.style.introDialog, item, count, typeName);    //创建Dialog并设置样式主题
        detailsDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
        detailsDialog.show();
        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                MyApplication.interfaceVersion + "\t" + "商品详情"));
    }

    public int getMaxBuyCount(String type){
        int count;
        if(type.equals("Y")){
            count = drinkCount;
        } else if(type.equals("N")){
            count = snackCount;
        } else {
            count = saleCount;
        }
        return count;
    }

    public String getItemTypeName(String type){
        String typeName;
        if(type.equals("Y")){
            typeName = getResources().getString(R.string.xf_drink);
        } else if(type.equals("N")){
            typeName = getResources().getString(R.string.xf_friut);
        } else {
            typeName = getResources().getString(R.string.xf_goods);
        }
        return typeName;
    }

    //接收刷卡事件
    public void onEventMainThread(XFReqCardEvent e) {
        Log.i(TAG, "查询卡号，cardid=" + e.getCard());
        switch (e.getType()) {
            case 1:
                toHttpGet(GET_HAND, null, e.getCard(), null);
                break;
            case 2:
                toHttpGet(GET_WAITER, null, e.getCard(), null);
                break;
        }
    }

    //接收隐藏类型事件XFUpdateTypeHideEvent
    public void onEventMainThread(XFUpdateTypeHideEvent e) {
        List<NmXFTypeBean> ml = e.gettList();
        JSONArray jarr = new JSONArray();
        for(NmXFTypeBean tb : ml){
            if(!tb.getShow()){
                jarr.put(tb.getId());
            }
        }
        if(!isSameAsBefore(jarr)) {
            if(handlerMsg.hasMessages(SET_TYPE_HIDE)){
                handlerMsg.removeMessages(SET_TYPE_HIDE);
            }
            typeHideArr = jarr.toString();
            handlerMsg.sendEmptyMessageDelayed(SET_TYPE_HIDE, 1500);
        }
    }

    //判断是否一样
    private boolean isSameAsBefore(JSONArray arr){
        boolean isSame = true;
        if (arr.length() > 0 && TextUtils.isEmpty(typeHideArr)){
            return false;
        }
        try {
            JSONArray jsonArray = new JSONArray(typeHideArr);
            if(jsonArray.length() != arr.length()){
                return false;
            }
            for (int i = 0; i < arr.length(); i++) {
                String id = arr.getString(i);
                if (!typeHideArr.contains(id)){
                    isSame = false;
                    break;
                }
            }
        }catch (JSONException e){

        }
        return isSame;
    }

    //接收隐藏商品事件 XFUpdateItemHideEvent
    public void onEventMainThread(XFUpdateItemHideEvent e) {
        if(e.getShow()){
            if (!TextUtils.isEmpty(itemHideArr) && itemHideArr.contains(e.getId())){
                try{
                    JSONArray jarr = new JSONArray(itemHideArr);
                    JSONArray jsonArray = new JSONArray();
                    for(int i =0;i<jarr.length();i++){
                        String hid = jarr.getString(i);
                        if(!hid.equals(e.getId())){
                            jsonArray.put(hid);
                        }
                    }
                    itemHideArr = jsonArray.toString();
                }catch (JSONException er){
                }
            }else{
                return;
            }
        }else{
            if(!TextUtils.isEmpty(itemHideArr)){
                if(itemHideArr.contains(e.getId())){
                    return;
                }
                try{
                    JSONArray jarr = new JSONArray(itemHideArr);
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.put(e.getId());
                    for(int i =0;i<jarr.length();i++){
                        String hid = jarr.getString(i);
                        if(!hid.equals(e.getId())){
                            jsonArray.put(hid);
                        }
                    }
                    itemHideArr = jsonArray.toString();
                }catch (JSONException er){
                }
            }else{
                JSONArray jsonArray = new JSONArray();
                jsonArray.put(e.getId());
                itemHideArr = jsonArray.toString();
            }
        }
        if(handlerMsg.hasMessages(SET_ITEM_HIDE)){
            handlerMsg.removeMessages(SET_ITEM_HIDE);
        }
        handlerMsg.sendEmptyMessageDelayed(SET_ITEM_HIDE,1500);
    }

    public void setTypeSortValue(String s) {
        typeSortArr = s;
        toHttpGet(SET_TYPE_SORT,null);
    }

    public void setItemSortValue(String s,String id){
        itemSortArr = s;
        toHttpGet(SET_ITEM_SORT,id);
    }

    //接收下单事件
    public void onEventMainThread(XFBuyReqEvent e) {
        Log.i(TAG, "下单，keyno=" + e.getKeyno());
        buyList = e.getBuylist();
        toHttpGet(GET_BUY, null, null, e.getKeyno());
    }

    public void buyGoods(List<NmXFBuyItemBean> ni){
        ProcessWaitingUtil.showProcessDialog(NmXiaoFeiActivity.this, "Loading...", 5000);
        buyList = ni;
        toHttpGet(GET_BUY, null, null, null);
    }

    //接收更新购物篮信息
    public void onEventMainThread(XFUpdateCartEvent e) {
        if(e.getTag() && e.getAnimTag()) {
            addAnimSatrt();
        }else{
            setCartCount();
        }
    }

    //加入购物车动画
    private void addAnimSatrt() {
        final ImageView view = new ImageView(this);
        view.setImageResource(R.drawable.xf_anim_cirl);
        int wid = getResources().getDimensionPixelSize(R.dimen.px45);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(wid, wid);
        myxfLayout.addView(view, layoutParams);

        float startX = (float) getResources().getDimensionPixelSize(R.dimen.px960);
        float startY = (float) getResources().getDimensionPixelSize(R.dimen.px600);


        float toX = (float) getResources().getDimensionPixelSize(R.dimen.px144);
        float toY = (float) getResources().getDimensionPixelSize(R.dimen.px159);

        Path path = new Path();
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                view.setTranslationX(mCurrentPosition[0]);
                view.setTranslationY(mCurrentPosition[1]);
            }
        });
        //五、 开始执行动画
        valueAnimator.start();

        // 六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                myxfLayout.removeView(view);
                shopCartBt.startAnimation(scaleAnimation);
                setCartCount();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    //显示购物车数量
    public void setCartCount() {
        int count = getCartCount();
        cartCountText.setText(count + "");
        if (count < 1) {
            cartCountText.setVisibility(View.INVISIBLE);
        } else {
            cartCountText.setVisibility(View.VISIBLE);
        }
    }

    //获取购物车总数量
    public int getCartCount() {
        int count = 0;
        List<NmXFBuyItemBean> mycartList = app.shopCartList;
        for (NmXFBuyItemBean mi : mycartList) {
            count += mi.getNum();
        }
        return count;
    }

    //加入购物车时判断当前类别的数量
    public int getCartCount(String type, int num) {
        int count = 0;
        List<NmXFBuyItemBean> mycartList = app.shopCartList;
        for (NmXFBuyItemBean mi : mycartList) {
            if (mi.getType().equals(type)) {
                count += mi.getNum();
            }
        }
        count += num;
        return count;
    }

    //获取购物篮总价
    public String getCartPrice() {
        double price = 0.00;
        List<NmXFBuyItemBean> mycartList = app.shopCartList;
        for (NmXFBuyItemBean mi : mycartList) {
            double p = mi.getPrice();
            double n = (double) mi.getNum();
            price += (p * n);
        }
        return String.format("%.0f",price);
    }

    /**
     * handler处理消息机制
     */
    private static class ThisHandler extends Handler {
        private WeakReference<NmXiaoFeiActivity> wrActivity;

        public ThisHandler(NmXiaoFeiActivity activity) {
            wrActivity = new WeakReference<NmXiaoFeiActivity>(activity);
        }

        @Override
        public void handleMessage(final Message message) {
            final NmXiaoFeiActivity act = wrActivity.get();
            if (act != null) {
                if(message.what == GET_TYPE_HIDE || message.what == GET_TYPE_SORT ||
                        message.what == GET_ITEM_HIDE || message.what == GET_ITEM_SORT ||
                        message.what == SET_TYPE_SORT || message.what == SET_ITEM_SORT){
                    act.parseResData(message.obj.toString(), message.arg1,message.what);
                }else if(message.what == SET_TYPE_HIDE) {
                    if(message.arg1 == 1){
                        act.parseResData(message.obj.toString(), message.arg1,message.what);
                    }else {
                        act.toHttpGet(SET_TYPE_HIDE, null);
                    }
                }else if(message.what == SET_ITEM_HIDE) {
                    if(message.arg1 == 1){
                        act.parseResData(message.obj.toString(), message.arg1,message.what);
                    }else {
                        act.toHttpGet(SET_ITEM_HIDE, null);
                    }
                }else{
                    act.parseResData(message.what, message.obj.toString(), message.arg1);
                }
            }
        }
    }
}
